<template>
  <div>
    <van-cell
      icon="search"
      v-for="(item, index) in hightLightSuggestions"
      :key="index"
      @click="$emit('update-keywords', suggestions[index])"
    >
      <template #title>
        <span v-html="item"></span>
      </template>
    </van-cell>
  </div>
</template>

<script>
import { getSuggestionsAPI } from '@/api'
import { debounce } from 'lodash'
export default {
  name: '',
  components: {},
  props: {
    keywords: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      suggestions: []
    }
  },
  computed: {
    hightLightSuggestions() {
      const reg = new RegExp(this.keywords, 'ig')
      return this.suggestions.map((str) => {
        return str.replace(
          reg,
          (match) => `<span style='color:red'>${match}</span>`
        )
      })
    }
  },
  watch: {
    keywords: {
      handler: 'getSearchSuggestion',
      immediate: true
    }
  },
  created() {},
  methods: {
    getSearchSuggestion: debounce(async function () {
      const { data } = await getSuggestionsAPI(this.keywords)
      this.suggestions = data.data.options.filter(Boolean)
    }, 300)
  }
}
</script>

<style scoped></style>
